use zmath::{Vec2, Vec4};

use zert::glutils::*;
use zert::graphics;
use zert::Camera2D;
use zert::shaders::{TEX_FRAGMENT_SHADER_SRC, SIMPLE_TEX_VERTEX_SHADER_SRC};

fn main() {
    use glfw::{ Action, Context, Key, WindowMode };

    let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS)
        .expect("Failed to init glfw");

    let (mut window, events) = glfw.create_window(600, 600, "Draw Texture", WindowMode::Windowed)
        .unwrap();

    window.make_current();

    zert::load(|s| window.get_proc_address(s));

    window.set_all_polling(true);

    let texture = {
        let img = image::open("images/dummy.bmp").unwrap().into_rgba();
        let (width, height) = img.dimensions();

        graphics::Texture::with_pixels(width, height, graphics::TextureFormat::RGBA, &img.into_raw())
    };

    let shader = ShaderProgram::from_source(SIMPLE_TEX_VERTEX_SHADER_SRC, TEX_FRAGMENT_SHADER_SRC);

    shader.set_uniform("tex", 0);

    let mesh = VertexArray::quad(Vec2(0.0, 0.0), Vec2(1.0, 1.0));

    while !window.should_close() {
        glfw.poll_events();
        for (_, event) in glfw::flush_messages(&events) {
            match event {
                glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => {
                    window.set_should_close(true)
                }
                _ => {},
            }
        }

        gl_clear_color(0.0, 1.0, 1.0, 1.0);
        gl_clear(gl::COLOR_BUFFER_BIT);

        shader.use_program();
        texture.bind(0);
        mesh.bind();
        mesh.draw(gl::TRIANGLES, 6);
        mesh.unbind();
        texture.unbind();


        window.swap_buffers();
    }
}